package com.monkey.demo.init;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.monkey.redis.init.AbstractCache;
import com.monkey.demo.entity.SysUser;
import com.monkey.demo.service.SysUserService;
import com.monkey.redis.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SysUserInit extends AbstractCache {
    private static final String KEY="SYSUSER";

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void initCache() {
        List<SysUser> sysUsers=sysUserService.selectList();
        if(sysUsers!=null && sysUsers.size()>0){
            redisUtil.set(KEY, JSON.toJSONString(sysUsers));
        }
    }

    @Override
    public List<SysUser>  getCache(String key) {
        String s = redisUtil.get(KEY);
        if(s!=null && s!=""){
            List<SysUser> sysUsers = JSONArray.parseArray(s, SysUser.class);
            return sysUsers;
        }
        return null;
    }

    @Override
    public void clearCache() {
        redisTemplate.delete(KEY);
    }

    @Override
    public void reloadCache() {
        super.reloadCache();
    }
}
